/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.fragment;

import java.util.List;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.StopTimesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopsIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TaskIntentHolder;
import lt.marsrutai.mobile.android.adapter.StopAdapter;
import lt.marsrutai.mobile.android.fragment.task.GetStopsTaskFragment;
import lt.marsrutai.mobile.android.fragment.task.TaskFragment;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.Stop;
import lt.marsrutai.mobile.android.task.GetStopsTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockListFragment;

public class StopsFragment extends SherlockListFragment {
    
    private static final String GET_STOPS_TASK_FRAGMENT_TAG = "getStopsTaskFragment";
    private FragmentManager fragmentManager;
    private ActivityManager manager;

    private List<Stop> stops;
    private StopAdapter adapter;

    private String scopeFolder;
    private String scopeName;
    private String transportId;
    private String scheduleId;
    private String scheduleName;
    private String scheduleTrackName;
    private String trackId;
    private String trackName;

    private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TaskIntentHolder holder = new TaskIntentHolder(intent);
            stops = holder.getListResult();

            if (holder.getStatus() == GetStopsTask.RESULT_NOT_RESOLVED) {
                manager.runOnUiThread(manager.errorRes);
            }
            else {
                fillAdapter();
                manager.dismissDownloadLoadingBar();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, null);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        fragmentManager = getFragmentManager();
        manager = new ActivityManager(getActivity());
        manager.showDownloadLoadingBar();
        
        receiveItemData(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(stopReceiver);
    }
    
    @Override
    public void onResume() {
        super.onResume();

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(stopReceiver, new IntentFilter(GetStopsTask.BROADCAST_ACTION));

        if (stops == null) {
            // Check whether the worker fragment has been retained
            TaskFragment<?, ?, ?> taskFragment = (TaskFragment<?, ?, ?>) fragmentManager.findFragmentByTag(GET_STOPS_TASK_FRAGMENT_TAG);
    
            // Start downloading only if we don't have any scopes, and task fragments has not been retained
            if (!TaskFragment.isActive(taskFragment)) {
                downloadData();
            }
        }
        else {
            // already have all the data - display it
            fillAdapter();
            manager.dismissDownloadLoadingBar();
        }
    }

    protected void downloadData() {
        TaskFragment.download(fragmentManager, 
                GetStopsTaskFragment.class, GET_STOPS_TASK_FRAGMENT_TAG,
                new GetStopsTask.Criteria[] {new GetStopsTask.Criteria(scopeFolder, trackId, null)});
    }

    private void fillAdapter() {
        adapter = new StopAdapter(getActivity(), bundleState());
        adapter.setStops(stops);
        
        setListAdapter(adapter);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        sendItemData(position);
    }

    public void receiveItemData(Bundle bundle) {
        StopsIntentHolder intentHolder = new StopsIntentHolder(bundle == null ? getArguments() : bundle);
        scopeFolder = intentHolder.getScopeFolder();
        scopeName = intentHolder.getScopeName();
        transportId = intentHolder.getTransportId();
        scheduleId = intentHolder.getScheduleId();
        scheduleName = intentHolder.getScheduleName();
        scheduleTrackName = intentHolder.getScheduleTrackName();
        trackId = intentHolder.getTrackId();
        trackName = intentHolder.getTrackName();
        stops = intentHolder.getStops();
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putAll(bundleState());
        super.onSaveInstanceState(outState);
    }

    protected Bundle bundleState() {
        StopsIntentHolder intentHolder = new StopsIntentHolder(new Bundle());
        intentHolder.setStops(stops);
        intentHolder.setScopeFolder(scopeFolder);
        intentHolder.setScopeName(scopeName);
        intentHolder.setTransportId(transportId);
        intentHolder.setScheduleId(scheduleId);
        intentHolder.setScheduleName(scheduleName);
        intentHolder.setScheduleTrackName(scheduleTrackName);
        intentHolder.setTrackId(trackId);
        intentHolder.setTrackName(trackName);
        return intentHolder.getIntent().getExtras();
    }

    public void sendItemData(int i) {
        Stop stop = stops.get(i);
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(getActivity());
        intentHolder.setScopeFolder(scopeFolder);
        intentHolder.setScopeName(scopeName);
        intentHolder.setTransportId(transportId);
        intentHolder.setScheduleId(scheduleId);
        intentHolder.setScheduleName(scheduleName);
        intentHolder.setScheduleTrackName(scheduleTrackName);
        intentHolder.setTrackId(trackId);
        intentHolder.setTrackName(trackName);
        intentHolder.setStopId(stop.getId());
        intentHolder.setStopName(stop.getName());
        intentHolder.setStopDirectionName(stop.getDirectionName());
        startActivity(intentHolder.getIntent());
    }

}
